﻿package
{
	import flash.utils.ByteArray;
	import flash.data.*;
	import flash.events.SQLEvent;
	import flash.events.SQLErrorEvent;
	import flash.filesystem.File; 
	
	[Bindable]
	[Table(name='settings')]
	dynamic class Settings extends Object
	{
		public var setting_name:String;
		public var setting_value:String;

		private static var dbFile:File;
		private static var conn:SQLConnection;
		
		public function Settings()
		{
			if (conn == null) 
			{
				conn = new SQLConnection(); 
					 
				conn.addEventListener(SQLEvent.OPEN, openHandler); 
				conn.addEventListener(SQLErrorEvent.ERROR, errorHandler); 
					 
				// The database file is in the application storage directory 
				dbFile = File.applicationStorageDirectory.resolvePath("settings.db"); 
				
				if(!dbFile.exists)
				{
					conn.open(dbFile, SQLMode.CREATE);
					conn.close();
				}
				conn.open(dbFile, SQLMode.UPDATE);

				var sqlStatement:SQLStatement = new SQLStatement();
				sqlStatement.addEventListener(SQLErrorEvent.ERROR, errorHandler);
				sqlStatement.sqlConnection = conn;
				sqlStatement.text = 'Create Table If Not Exists settings(setting_name TEXT PRIMARY KEY, setting_value STRING)';
				sqlStatement.execute();
			}
		}
		
		public function execute_query(sql)
		{
			trace(sql);
			Tasks(null);
			var sqlStatement:SQLStatement = new SQLStatement();
			sqlStatement.addEventListener(SQLErrorEvent.ERROR, errorHandler);
			sqlStatement.sqlConnection = conn;
			sqlStatement.text = sql;
			sqlStatement.execute();
			return sqlStatement.getResult().data;
		}
		
		public function insert(setting_name, setting_value)
		{
			trace('Setting inserted...');
			TimerLog(null);
			var sqlStatement:SQLStatement = new SQLStatement();
			sqlStatement.addEventListener(SQLErrorEvent.ERROR, errorHandler);
			sqlStatement.sqlConnection = conn;

			sqlStatement.text = "Insert Or Replace Into settings Values(@SETTINGNAME, @SETTINGVALUE);";
			sqlStatement.parameters['@SETTINGNAME'] = setting_name;
			sqlStatement.parameters['@SETTINGVALUE'] = setting_value;
			sqlStatement.execute();
		}
		
		public function get_setting(setting_name)
		{
			var setting = execute_query("Select * From settings Where setting_name='"+setting_name+"'");
			try
			{
				return setting[0].setting_value;
			}
			catch(e)
			{
				// no such setting apparently
			}
		}
			 
		function openHandler(event:SQLEvent):void 
		{ 
			//trace("the database was created successfully"); 
		} 
			 
		function errorHandler(event:SQLErrorEvent):void 
		{ 
			new Errors("Error message: "+event.error.message+"\nDetails: "+event.error.details); 
		} 
	}
}